package cn.edu.zut.logistics.controller;

import cn.edu.zut.logistics.entity.*;
import cn.edu.zut.logistics.mapper.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/indicators")
@RequiredArgsConstructor
@CrossOrigin
public class IndicatorController {

    // ====== 9 张表 Mapper ======
    private final BusinessTypeDistributionMetricsMapper businessMapper;
    private final CityDeliveryQuantityMetricsMapper cityMapper;
    private final CustomerBehaviorAnalysisMetricsMapper behaviorMapper;
    private final IncomeExpenseMetricsMapper incomeMapper;
    private final OutletOperationMetricsMapper outletMapper;
    private final PackageProcessingStatusMetricsMapper pkgStatusMapper;
    private final PackageProcessingTotalMetricsMapper pkgTotalMapper;
    private final TransportationEfficiencyMetricsMapper transMapper;
    private final WarehouseOperationMetricsMapper whMapper;

    /* 1. 业务类型分布 - 饼图 */
    @GetMapping("/businessType")
    public List<Map<String,Object>> businessType() {
        // 获取今天的数据，如果没有则获取最近一天的数据
        List<Map<String,Object>> result = businessMapper.selectMaps(Wrappers.<BusinessTypeDistributionMetrics>lambdaQuery()
                .eq(BusinessTypeDistributionMetrics::getStatisticsDate, LocalDate.now()));
        
        if (result.isEmpty()) {
            // 如果今天没有数据，获取最近的数据
            result = businessMapper.selectMaps(Wrappers.<BusinessTypeDistributionMetrics>lambdaQuery()
                    .orderByDesc(BusinessTypeDistributionMetrics::getStatisticsDate)
                    .last("LIMIT 10"));
        }
        return result;
    }

    /* 2. 城市派件量排名 - 横向柱图 */
    @GetMapping("/cityDelivery")
    public List<Map<String,Object>> cityDelivery() {
        List<Map<String,Object>> result = cityMapper.selectMaps(Wrappers.<CityDeliveryQuantityMetrics>lambdaQuery()
                .eq(CityDeliveryQuantityMetrics::getStatisticsDate, LocalDate.now())
                .orderByAsc(CityDeliveryQuantityMetrics::getRanking));
        
        if (result.isEmpty()) {
            // 获取最近的数据
            result = cityMapper.selectMaps(Wrappers.<CityDeliveryQuantityMetrics>lambdaQuery()
                    .orderByDesc(CityDeliveryQuantityMetrics::getStatisticsDate)
                    .orderByAsc(CityDeliveryQuantityMetrics::getRanking)
                    .last("LIMIT 10"));
        }
        return result;
    }

    /* 3. 客户行为分析 - 双轴图 */
    @GetMapping("/customerBehavior")
    public List<Map<String,Object>> customerBehavior() {
        // 获取所有数据用于分析
        return behaviorMapper.selectMaps(Wrappers.<CustomerBehaviorAnalysisMetrics>lambdaQuery()
                .orderByDesc(CustomerBehaviorAnalysisMetrics::getStatisticsMonth)
                .last("LIMIT 20"));
    }

    /* 4. 收入支出指标 - KPI 卡片 */
    @GetMapping("/incomeExpense")
    public Map<String,Object> incomeExpense() {
        return incomeMapper.selectMaps(Wrappers.<IncomeExpenseMetrics>lambdaQuery()
                .eq(IncomeExpenseMetrics::getStatisticsDate, LocalDate.now())
                .last("LIMIT 1")).stream().findFirst().orElse(Map.of());
    }

    /* 5. 网点运营指标 - 表格 */
    @GetMapping("/outletOperation")
    public List<Map<String,Object>> outletOperation() {
        List<Map<String,Object>> result = outletMapper.selectMaps(Wrappers.<OutletOperationMetrics>lambdaQuery()
                .eq(OutletOperationMetrics::getStatisticsDate, LocalDate.now())
                .orderByDesc(OutletOperationMetrics::getEmployeeEfficiencyScore)
                .last("LIMIT 5"));
        
        if (result.isEmpty()) {
            // 获取最近的数据
            result = outletMapper.selectMaps(Wrappers.<OutletOperationMetrics>lambdaQuery()
                    .orderByDesc(OutletOperationMetrics::getStatisticsDate)
                    .orderByDesc(OutletOperationMetrics::getEmployeeEfficiencyScore)
                    .last("LIMIT 5"));
        }
        return result;
    }

    /* 6. 包裹处理状态 - 堆叠面积图 */
    @GetMapping("/packageProcessingStatus")
    public List<Map<String,Object>> packageProcessingStatus() {
        // 获取最近一周的数据
        return pkgStatusMapper.selectMaps(Wrappers.<PackageProcessingStatusMetrics>lambdaQuery()
                .orderByDesc(PackageProcessingStatusMetrics::getStatisticsTime)
                .last("LIMIT 20"));
    }

    /* 7. 包裹处理总量 - 趋势图 */
    @GetMapping("/packageProcessingTotal")
    public List<Map<String,Object>> packageProcessingTotal() {
        return pkgTotalMapper.selectMaps(Wrappers.<PackageProcessingTotalMetrics>lambdaQuery()
                .eq(PackageProcessingTotalMetrics::getStatisticsDate, LocalDate.now())
                .orderByAsc(PackageProcessingTotalMetrics::getCreateTime));
    }

    /* 8. 运输效率 - 雷达图 */
    @GetMapping("/transportationEfficiency")
    public List<Map<String,Object>> transportationEfficiency() {
        List<Map<String,Object>> result = transMapper.selectMaps(Wrappers.<TransportationEfficiencyMetrics>lambdaQuery()
                .eq(TransportationEfficiencyMetrics::getStatisticsDate, LocalDate.now()));
        
        if (result.isEmpty()) {
            // 获取最近的数据
            result = transMapper.selectMaps(Wrappers.<TransportationEfficiencyMetrics>lambdaQuery()
                    .orderByDesc(TransportationEfficiencyMetrics::getStatisticsDate)
                    .last("LIMIT 10"));
        }
        return result;
    }

    /* 9. 仓储运营 - 柱折混合 */
    @GetMapping("/warehouseOperation")
    public List<Map<String,Object>> warehouseOperation() {
        // 获取最近几个月的数据
        return whMapper.selectMaps(Wrappers.<WarehouseOperationMetrics>lambdaQuery()
                .orderByDesc(WarehouseOperationMetrics::getStatisticsDate)
                .last("LIMIT 12"));
    }
}